<template>
	<view class="btn_box">
		<template v-if="page !=='del'">
			<button class="btn" type="primary" size="mini" @click="add">新增</button>
			<button class="btn" style="background-color: #949065; color: #fff;" size="mini" @click="deleteClent">删除</button>
			<button class="btn" style="background-color: #3b9457; color: #fff;" size="mini" @click="getdata">全部数据</button>
			<!-- <button class="btn" size="mini" @click="toThreadPool">退回线索池</button> -->
		</template>
		<template v-else>
			<button class="btn" type="primary" size="mini" @click="recover">恢复</button>
		</template>
	</view>
	
	<uni-popup type="center" ref="addPopup">
		<view class="add_form_box">
			<view class="title"> 添加客户 </view>
			<uni-forms label-width="100px" label-align="right"  class="add_form"  ref="add_form" :modelValue="baseFormData" :rules="rules">
			
				<uni-forms-item label="姓名" required name="name" >
					<uni-easyinput v-model="baseFormData.name" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="性别" required name="sex">
					<uni-data-checkbox v-model="baseFormData.sex" :localdata="sexs" />
				</uni-forms-item>
				<uni-forms-item label="手机号" required name="phone" >
					<uni-easyinput v-model="baseFormData.phone" placeholder="请输入手机号码" />
				</uni-forms-item>
				<uni-forms-item label="年龄" required name="age"> 
					<uni-easyinput v-model="baseFormData.age" placeholder="请输入年龄" />
				</uni-forms-item>
				<uni-forms-item label="资金需求" required name="demand">
					<uni-easyinput v-model="baseFormData.demand" placeholder="请输入资金需求" />
				</uni-forms-item>
				<uni-forms-item label="城市" required  name="city">
					<uni-data-picker
						placeholder="请选择城市"
						popup-title="请选择所在地区"
						:localdata="citys"
						v-model="baseFormData.city"
					></uni-data-picker>
				</uni-forms-item>
				
				<uni-forms-item label="学历" required  name="education">
					<uni-data-checkbox v-model="baseFormData.education" :localdata="educations" />
				</uni-forms-item>
				
				<uni-forms-item label="身份" required  name="identity">
					<uni-data-checkbox v-model="baseFormData.identity" :localdata="identitys" />
				</uni-forms-item>
				
				<uni-forms-item label="单位类型" required  name="work">
					<uni-data-checkbox v-model="baseFormData.work" :localdata="works" />
				</uni-forms-item>
				
				<uni-forms-item label="税前收入" required  name="income">
					<uni-data-checkbox v-model="baseFormData.income" :localdata="incomes" />
				</uni-forms-item>
				
				<uni-forms-item label="征信" required  name="credit">
					<uni-data-checkbox v-model="baseFormData.credit" :localdata="credits" />
				</uni-forms-item>
				
				<uni-forms-item label="资质(可多选)" required name="certification">
					<uni-data-checkbox multiple  v-model="baseFormData.certification" :localdata="certifications" />
				</uni-forms-item>
				
			
				<uni-forms-item label="备注">
					<uni-easyinput type="textarea" v-model="baseFormData.remark" placeholder="备注信息" />
				</uni-forms-item>
			</uni-forms>
			<view class="add_btn">
				<button type="primary" @click="addClient"> 保存 </button>
			</view>
		</view>
	</uni-popup>
	
	<view class="table-box">
		<uni-table ref="clentTable" border stripe emptyText="暂无更多数据" class="table" :loading="isReqState" type="selection">
			<!-- 表头 -->
			<uni-tr>
				<uni-th align="center">序号</uni-th>
				<uni-th align="center">姓名</uni-th>
				<uni-th align="center">性别</uni-th>
				<uni-th align="center">年龄</uni-th>
				<uni-th align="center">手机号</uni-th>
				<uni-th align="center">跟进时间</uni-th>
				<uni-th align="center">等级</uni-th>
				<uni-th sortable align="center">资金需求</uni-th>
				<uni-th align="center">城市</uni-th>
				<uni-th align="center">学历</uni-th>
				<uni-th align="center">身份</uni-th>
				<uni-th align="center">单位类型</uni-th>
				<uni-th align="center">税前收入</uni-th>
				<uni-th align="center">征信</uni-th>
				<uni-th align="center">资质</uni-th>
				<uni-th align="center" style="max-width: 100px;">备注</uni-th>
				<uni-th align="center" style="width: 200px;">提交时间</uni-th>
				<template v-if="page !=='del'">
					<uni-th align="center">操作</uni-th>
				</template>
			</uni-tr>
			
			<!-- 数据 -->
			<uni-tr v-for="(k, index) in threadData" :key="index" >
				<uni-td align="center">{{(stateCurrent-1)*statePageSize+index+1}}</uni-td>
				<uni-td align="center">{{k.name}}</uni-td>
				<uni-td align="center">{{ getValueText(k.sex, sexs)}}</uni-td>
				<uni-td align="center">{{k.age}}</uni-td>
				<uni-td align="center">{{k.phone}}</uni-td>
				<!-- <uni-td align="center" :class="Date.now()-k.latestTime > 1000*60*60*24*3 ? 'red' : '' "><uni-dateformat :date="k.latestTime" :threshold="[3600000, 86400000]"></uni-dateformat></uni-td> -->
				<uni-td align="center" :class="Date.now()-k.latestTime > 1000*60*60*24*3 ? 'red' : '' ">{{formatTimestamp(k.latestTime)}}</uni-td>
				<uni-td align="center"><uni-rate :readonly="true" :value="k.class" /></uni-td>
				<!-- 资金需求 -->
				<uni-td align="center">{{ k.demand }}</uni-td>
				<!-- 城市 -->
				<uni-td align="center">{{ findCityAndDistrict(k.city, citys) }}</uni-td>
				<!-- 学历 -->
				<uni-td align="center">{{ getValueText(k.education, educations) }}</uni-td>
				<!-- 身份 -->
				<uni-td align="center">{{ getValueText(k.identity, identitys) }}</uni-td>
				<!-- 工作 -->
				<uni-td align="center">{{ getValueText(k.work, works) }}</uni-td>
				<!-- 收入 -->
				<uni-td align="center">{{ getValueText(k.income, incomes) }}</uni-td>
				<!-- 信用 -->
				<uni-td align="center">{{ getValueText(k.credit, credits) }}</uni-td>
				<!-- 资质 -->
				<uni-td align="center">{{ getTextsFromValues(k.certification, certifications) }}</uni-td>
				<uni-td align="center" style="max-width: 500px; ">{{k.remark}}</uni-td>
				<uni-td align="center" style="width: 200px; ">{{timestampToDate(k.upload_time)}}</uni-td>
				<template v-if="page !=='del'">
					<uni-td align="center"><button type="primary" size="mini" hover-stop-propagation  @click="showPoput(k)">编辑</button></uni-td>
				</template>
	
			</uni-tr>
		
		</uni-table>
	</view>
	
	<view class="uni-pagination-box">
		<!-- 
			show-icon：使用icon代替“上一页”、“下一页”
			show-page-size：显示条数框选择器
			pageSizeRange：条数框数组
			page-size：当前每页条数
			v-model：当前页码数
			total：页码总数
			@change：页码改变时的钩子
			@pageSizeChange：每页条数改变时的钩子
		-->
		<uni-pagination 
			show-icon
			show-page-size
			:pageSize="pageSize"
			v-model="current"
			:total="total"
			@change="onPageChanged"
			@pageSizeChange="changeSize"
		/>
	</view>
</template>

<script>
const customerInfo = uniCloud.importObject('zf_customerInfo')
import { mapState, mapActions } from 'vuex';
import {getValueText, findCityAndDistrict, getTextsFromValues, timestampToDate, formatTimestamp} from'@/utils/common.js'
import { 
	sexs,
	educations,
	identitys,
	works,
	incomes,
	credits,
	certifications,
	citys,
} from '@/common/formItemSelect.js'
export default{
	data(){
		return {
			// 页码
			current: 1,
			// 每页数据数
			pageSize: 5,
			baseFormData:{
				name:'',
				sex:'',
				phone:'',
				age:'',
				// 资金
				demand:'',
				// 城市
				city:'',
				// 学历
				education:'',
				// 身份
				identity:'',
				// 单位类型
				work: '',
				// 税前收入
				income: '',
				// 征信
				credit:'',
				// 资质
				certification:'',
				// 备注信息
				remark: ''
			},
			rules:{
				name:{
					rules:[
						{ required: true, errorMessage: '请填写名字' },
						{
							validateFunction(rule,value,data,callback){
								if (!/^[\u4e00-\u9fa5]+(\s[\u4e00-\u9fa5]+)*$/.test(value)) {
									callback('请正确填写中文名字')
								}
								return true
							}	
						},
					],
				},
				sex:{rules:[{required: true, errorMessage: '请选择性别'}]},
				phone:{
					rules:[
						{ required: true, errorMessage: '请填写11位手机号', pattern: '/^1[3-9]\d{9}$/'},
						{
							validateFunction(rule,value,data,callback){
								if (!/^1[3-9]\d{9}$/.test(value)) {
									callback('请正确填写11位手机号')
								}
								return true
							}		
						}
					]
				},
				age:{
					rules:[
						{ required: true, errorMessage: '请填写年龄' },
						{
							validateFunction(rule,value,data,callback){
								if (!/^(0|[1-9]\d?|1[0-4]\d|150)$/.test(value)) {
									callback('请正确填写年龄')
								}
								return true
							}	
						},
					],
				},
				// 资金
				demand:{
					rules:[
						{ required: true,errorMessage: '请填写资金需求' },
						{
							validateFunction(rule,value,data,callback){
								if (!/^\d+$/.test(value)) {
									callback('请填写正确的资金需求')
								}
								return true
							}	
						},
					],
				},
				// 城市
				city:{rules:[{required: true,errorMessage: '请填写所在城市'}]},
				// 学历
				education:{rules:[{required: true,errorMessage: '请选择学历'}]},
				// 身份
				identity:{rules:[{required: true,errorMessage: '请选择身份类型'}]},
				// 单位类型
				work:{rules:[{required: true,errorMessage: '请选择单位类型'}]},
				// 税前收入
				income: {rules:[{required: true,errorMessage: '请选择税前收入'}]},
				// 征信
				credit:{rules:[{required: true,errorMessage: '请选择征信情况'}]},
				// 资质
				certification:{rules:[{required: true,errorMessage: '请选择资质情况'}]},
				// 备注信息
				remark: ''
			},
			sexs: [],
			educations: [],
			identitys: [],
			works: [],
			incomes: [],
			credits: [],
			certifications: [],
			citys: [],
		}
	},
	computed:{
		...mapState({
			tableHeard: state => state.threadMy.tableHeard,
			threadData: state => state.threadMy.thread_tree_data,
			stateCurrent: state => state.threadMy.current,
			statePageSize: state => state.threadMy.pageSize,
			total: state => state.threadMy.total,
			isReqState: state => state.threadMy.isReqState,
			page: state => state.threadMy.page,
		})
	},
	
	mounted(){
		this.current = this.stateCurrent
		this.pageSize = this.statePageSize
		
		this.sexs = sexs
		this.educations = educations
		this.identitys = identitys
		this.works = works
		this.incomes = incomes
		this.credits = credits
		this.certifications = certifications
		this.citys = citys
	},
	
	
	methods:{
		getValueText,
		findCityAndDistrict,
		getTextsFromValues, 
		timestampToDate,
		formatTimestamp,
		
		// 注入的事件，点击搜索时重置页码
		resetPagination() {
			this.current = 1;
		}, 
		
		formattedArray(array){
			return array.map(item => `${item}`).join(', ') 
		},
		
		// 页码改变时的钩子
		onPageChanged(e){
			this.current = e.current
			this.$store.commit('threadMy/setCurrent', e.current)
			this.$store.dispatch('threadMy/reqGetThreaData')
		},
		
		// 每页条数改变时的钩子
		changeSize(e){
			this.pageSize = e
			this.$store.commit('threadMy/setPageSize', e)
			this.current = 1
			this.$store.commit('threadMy/setCurrent', 1)
			this.$store.dispatch('threadMy/reqGetThreaData')
		},
		
		// 点击时编辑按钮
		showPoput(e){
			this.$store.commit('threadMy/setClientInfo', e)
			this.$store.dispatch('threadMy/getFollowRecord')
		},
		
		// 添加按钮点击事件
		add(){
			this.baseFormData = {
				name:'',
				sex:'',
				phone:'',
				age:'',
				// 资金
				demand:'',
				// 城市
				city:'',
				// 学历
				education:'',
				// 身份
				identity:'',
				// 单位类型
				work: '',
				// 税前收入
				income: '',
				// 征信
				credit:'',
				// 资质
				certification:'',
				// 备注信息
				remark: ''
			}
			this.$refs.addPopup.open()
		},
		
		// 添加按钮表单保存事件
		addClient(){
			this.$refs.add_form.validate().then((res)=>{
				uni.showLoading({
					mask: true,
					title: '资料提交中'
				})
				// this.baseFormData.upload_time = Date.now()
				
				uniCloud.database().collection("zf_customerInfo").add(this.baseFormData).then((res)=>{
					this.$store.dispatch('threadMy/getThreadData')
					uni.hideLoading()
					uni.showToast({ title:'提交成功' })
					setTimeout(()=>{
						this.$refs.addPopup.close()
					},2000)
					
				}).catch(err=>{
					uni.hideLoading()
					uni.showToast({
						title: err+ '',
						icon: "none"
					})
				})
			}).catch((err)=>{
				console.log(err);
				uni.showToast({
					title: "请按要求填写完整信息",
					icon: "none"
				})
			})

		},
		
		// 删除按钮
		deleteClent(){
			// console.log(this.$refs.clentTable.backIndexData);
			if(this.$refs.clentTable.backIndexData.length === 0){
				uni.showToast({ title: "请选择用户", icon: "none" })
				return 
			}
			let arr = this.$refs.clentTable.backIndexData.map(item=>{
				return this.threadData[item]._id
			})
			// console.log(arr);
			uni.showModal({
				title: '提示',
				content: '你确定删除吗？',
				success: res=> {
					if (res.confirm) {
						customerInfo.removeStatesByIds({
							'type': 'delete',
							'ids': arr
						}).then(res=>{
							// console.log(res);
							// console.log(this.threadData.length);
							// 清空选中状态
							this.$refs.clentTable.clearSelection()
							console.log(this.$refs.clentTable);
							if(arr.length === this.threadData && this.$store.state.current>1){
								this.$store.commit('threadMy/setCurrent',this.$store.state.current-1 )
							}
							this.$store.dispatch('threadMy/getThreadData')
						}).catch(err=>{
							// console.log(err);
						})
					}
				}
			})
		},
		
		// 恢复按钮
		recover(){
			if(this.$refs.clentTable.backIndexData.length === 0){
				uni.showToast({ title: "请选择用户", icon: "none" })
				return 
			}
			let arr = this.$refs.clentTable.backIndexData.map(item=>{
				return this.threadData[item]._id
			})
			uni.showModal({
				title: '提示',
				content: '你确定恢复这些客户吗？',
				success: res=> {
					if (res.confirm) {
						customerInfo.removeStatesByIds({
							'type': 'recover',
							'ids': arr
						}).then(res=>{
							console.log(res);
							// console.log(this.threadData.length);
							// 清空选中状态
							this.$refs.clentTable.clearSelection()
							if(arr.length === this.threadData && this.$store.state.current>1){
								this.$store.commit('threadMy/setCurrent',this.$store.state.current-1 )
							}
							this.$store.dispatch('threadMy/getThreadData')
						}).catch(err=>{
							// console.log(err);
						})
					}
				}
			})
		},
		
		// 退回线索池
		toThreadPool(){
			
		},
		
		// 获取全部数据
		getdata(){
			this.$store.dispatch('threadMy/getThreadData')
			this.$store.commit('threadMy/setShowHintInfo', false);
		}
	}
}
</script>

<style lang="scss" scoped>
.btn_box{
	width: 100%;
	display: flex;
	justify-content: flex-start;
	.btn{
		margin: 10px 10px 0 0;
		width: 120px;
	}
}

.add_form_box{
	background-color: #fff;
	padding: 20px 30px 10px;
	height: 600px;
	border-radius: 30px;
	display: flex;
	flex-direction: column;
	.title{
		font-size: 22px;
		font-weight: 600;
		margin-bottom: 10px;
	}
	.add_form{
		flex: 1;
		overflow: auto;
		// height: calc(100% - 80px);
		.uni-data-checklist{
			margin-top: 6px !important;
		}
	}
	.add_btn{
		width: 100px;
		height: 34x;
		margin: 10px auto 0;
		uni-button{
			width: 100%;
			height: 100%;
			line-height: 34px;
		}
	}
}

.table-box{
	margin-top: 10px;
	box-sizing: border-box;
	flex: 1;
	overflow: auto;	
	display: flex;
	
	
	::v-deep .table{
		flex: 1;
		min-height: auto;
		box-sizing: border-box;
		overflow: auto;
		border: 1px solid rgba(#87CEEB, .3);
		box-shadow: 2px 2px 20px #87CEEB;
	}
}

/* 分页容器 */
.uni-pagination-box {
	margin-top: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
}

// 表格文字颜色：提醒
.red{
	color: red
}
</style>

<style scoped lang="scss">
// 首行固定,不透明
tr:nth-child(1){
	position:sticky;
	top:0;
	z-index: 3;
	background-color:#ecf5ff;
}

// 最后一列固定
th:nth-last-child(1), td:nth-last-child(1){
	position:sticky;
	right:0;
	z-index:2;
	width: 180rpx;
	background-color: #e2fdf0; 
}

// 设置左上角不透明
tr:last-child th:last-child{
	background-color: #fff;
}

// 设置首列固定
th:nth-child(1){
	position:sticky;
	left: 0;
	background-color: red;
}
th:nth-child(1){
	position:sticky;
	left:0;
	z-index: 3;
	background-color: red;
}
</style>